package handler

import (
	"sep15-homework/model"
	"sep15-homework/pkg"

	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := pkg.Md5(c.PostForm("password"))

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名和密码不能为空",
		})
		return
	}

	user := model.User{
		Username: username,
		Password: password,
	}
	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := pkg.Md5(c.PostForm("password"))

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	var user model.User
	model.DB.Where("username=?", username).First(&user).Debug()
	if username != user.Username {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if password != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
